<template>
  <n-card :bordered="false">
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>
  </n-card>
  <n-card :bordered="false" class="mt-3">
    <BasicTable
      :columns="articleColumns"
      :request="loadDataTable"
      :row-key="(row:ArticleData) => row.articleID"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
      :striped="true"
    >
      <template #tableTitle>
        <n-space>
          <n-button type="primary" @click="handleRefresh">
            <template #icon>
              <n-icon>
                <ReloadOutlined />
              </n-icon>
            </template>
            刷新
          </n-button>
        </n-space>
      </template>
    </BasicTable>
  </n-card>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form';
import { articleColumns, ArticleData } from './columns';
import { ReloadOutlined } from '@vicons/antd';
import { useMessage } from 'naive-ui';
import { AdminManagementApi } from '@/api/new/AdminManagementApi';
import { useRouter } from 'vue-router';

const actionRef = ref();
const message = useMessage();
const router = useRouter();

// 表单配置
const schemas: FormSchema[] = [
  {
    field: 'title',
    component: 'NInput',
    label: '文章标题',
    componentProps: {
      placeholder: '请输入文章标题',
    },
  },
  {
    field: 'authorID',
    component: 'NInputNumber',
    label: '作者ID',
    componentProps: {
      placeholder: '请输入作者ID',
      showButton: false,
    },
  },
  {
    field: 'status',
    component: 'NSelect',
    label: '状态',
    componentProps: {
      placeholder: '请选择状态',
      options: [
        {
          label: '全部',
          value: '',
        },
        {
          label: '草稿',
          value: 'draft',
        },
        {
          label: '已发布',
          value: 'published',
        },
        {
          label: '待审核',
          value: 'pendingReview',
        },
        {
          label: '已删除',
          value: 'deleted',
        },
      ],
    },
  },
];

// 操作列配置
const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction as any, {
      style: 'button',
      actions: [
        {
          label: '查看',
          onClick: handleView.bind(null, record),
          ifShow: () => true,
        },
        {
          label: '通过',
          onClick: handleApprove.bind(null, record),
          type: 'success',
          ifShow: () => record.status === 'pendingReview',
        },
        {
          label: '拒绝',
          onClick: handleReject.bind(null, record),
          type: 'error',
          ifShow: () => record.status === 'pendingReview',
        },
      ],
    });
  },
});

const [register, { getFieldsValue }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:3 2xl:3' },
  labelWidth: 80,
  schemas,
});

// 加载表格数据
const loadDataTable = async (res) => {
  try {
    // 获取未审核的文章
    const response = await AdminManagementApi.getPendingArticles();
    
    // 过滤条件
    const { title, authorID, status } = getFieldsValue();
    let filteredData = response;
    
    if (title) {
      filteredData = filteredData.filter(item => 
        item.title.toLowerCase().includes(title.toLowerCase())
      );
    }
    
    if (authorID) {
      filteredData = filteredData.filter(item => 
        item.authorID === authorID
      );
    }
    
    if (status) {
      filteredData = filteredData.filter(item => 
        item.status === status
      );
    }
    
    return {
      list: filteredData,
      page: res.page,
      pageSize: res.pageSize,
      pageCount: Math.ceil(filteredData.length / res.pageSize),
      itemCount: filteredData.length,
    };
  } catch (error) {
    message.error('获取文章列表失败');
    return {
      list: [],
      page: 1,
      pageSize: 10,
      pageCount: 0,
      itemCount: 0,
    };
  }
};

// 选中行事件
function onCheckedRow(rowKeys) {
  console.log('选中的行:', rowKeys);
}

// 刷新表格
function handleRefresh() {
  actionRef.value.reload();
  message.success('刷新成功');
}

// 查看文章详情
function handleView(record: ArticleData) {
  router.push({
    name: 'article_detail',
    params: {
      id: record.articleID
    }
  });
}

// 通过审核
async function handleApprove(record: ArticleData) {
  try {
    await AdminManagementApi.publishArticle(record.articleID);
    message.success('审核通过成功');
    handleRefresh();
  } catch (error) {
    message.error('操作失败: ' + error.message);
  }
}

// 拒绝审核
async function handleReject(record: ArticleData) {
  try {
    await AdminManagementApi.draftArticle(record.articleID);
    message.success('已拒绝并退回为草稿');
    handleRefresh();
  } catch (error) {
    message.error('操作失败: ' + error.message);
  }
}

// 提交表单
function handleSubmit() {
  actionRef.value.reload();
}

// 重置表单
function handleReset() {
  actionRef.value.reload();
}
</script>

<style lang="less" scoped></style>
